<template>
  <div class="personnel-entry-exit-review bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">人员出入园管理-审核</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">

      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>
    <!--  -->
    <div class="mb-4 space-x-2">
      <el-button @click="exportData(applications, '人员审核', selectedIds)">导出</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <!-- <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column> -->
        <el-table-column prop="STAFF_NAME" label="人员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ID_CARD" label="证件号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="TELEPHONE" label="联系方式" header-align="center" align="center"></el-table-column>
        <el-table-column prop="UPDATE_DATE" label="提交时间" header-align="center" align="center">
          <template #default="scope">
            <div>{{ dayjs(scope.row.UPDATE_DATE).format('YYYY-MM-DD HH:mm:ss') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="REVIEWER" label="审核人" header-align="center" align="center"></el-table-column>
        <el-table-column prop="REVIEWER_CODE" label="审核编号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AUTHORIZATION_TYPE" label="授权类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AU_STATUS" label="状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.AU_STATUS)">
              {{ scope.row.AU_STATUS }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.AU_STATUS == '待审核'" type="primary" size="small"
              @click="reviewApplication(scope.row)" link>审核</el-button>
            <el-button v-else type="primary" size="small" @click="reviewApplicationss(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->

    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />
    <!-- Review Dialog -->
    <el-dialog class="dialog-from" v-model="isReviewDialogOpen" title="审核" width="650" destroy-on-close align-center>
      <form>
        <h3 class="text-lg font-bold mb-4">预约详情</h3>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>系统单号：</strong>{{ reviewForm.ID }}</div>
          <div><strong>人员编码：</strong>{{ reviewForm.STAFF_CODE }}</div>
          <div><strong>人员姓名：</strong>{{ reviewForm.STAFF_NAME }}</div>
          <div><strong>证件号码：</strong>{{ reviewForm.ID_CARD }}</div>
          <div><strong>性别：</strong>{{ reviewForm.STAFF_GENDER }}</div>
          <div><strong>联系方式：</strong>{{ reviewForm.TELEPHONE }}</div>
          <div><strong>人员类型：</strong>{{ reviewForm.STAFF_TYPE }}</div>
          <div><strong>所属单位：</strong>{{ reviewForm.AFFILIATION }}</div>
          <div><strong>职位名称：</strong>{{ reviewForm.STAFF_POSITION }}</div>
          <div><strong>专业：</strong>{{ reviewForm.STAFF_MAJOR }}</div>
          <div><strong>其他证件：</strong>
            <div style="margin:10px 0">
              <div>{{ reviewForm.PAPERS }}</div>
              <el-button style="width: 75px; height: 30px;"
                @click="uploadfile(apiBaseUrl + '/download/' + reviewForm.PAPERS)">
                下载查看
              </el-button>
            </div>
          </div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>申请信息</span>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>

            <div>
              <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">授权类型：</label>
              <el-select style="width:  200px" :disabled="isViewDialogOpen"
                v-model="reservationreviewForm.AUTHORIZATION_TYPE" class="set-select" placeholder="请选择">
                <el-option label="长期" value="长期" />
                <el-option label="临时" value="临时" />
              </el-select>
            </div>
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">到期日期：</label>
            <el-input :disabled="isViewDialogOpen" style="margin: 0;padding: 0;" type="datetime-local"
              v-model="reservationreviewForm.END_TIME" class="input" />
          </div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>其他信息</span>
        </div>
        <div><strong>备注：</strong>{{ reviewForm.STAMP }}</div>
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click.prevent="submitReview('通过')" v-if="!isViewDialogOpen">审核通过</el-button>
          <el-button type="primary" @click.prevent='submitReview("未通过")' v-if="!isViewDialogOpen">审核拒绝</el-button>
          <el-button @click="closeReviewDialog">取消</el-button>
        </div>
      </form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'

const { proxy } = getCurrentInstance()

import { dayjs } from "element-plus"
import { exportData } from '#/utils/exportfile.js'
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/personnel-entry-exit'
})
const reservationreviewForm = ref({
  ID: '',
  AU_STATUS: '',
  APPLICATION_STATUS: '',
  AUTHORIZATION_TYPE: '', //授权类型：
  END_TIME: '', //申请区域：
})
const search = ref({
  STAFF_NAME: '',
  ID_CARD: '',
  AU_STATUS: ''
})
const formItems = ref([
  {
    label: '人员姓名:',
    model: 'STAFF_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '证件号码：',
    model: 'ID_CARD',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '状态：',
    model: 'AU_STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '待审核', value: '待审核' },
      { label: '通过', value: '通过' },
      { label: '未通过', value: '未通过' },
    ],
  },
])
const imgdata = ref([])
const applications = ref([])
const isReviewDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const reviewForm = ref({
  ID: "",
  STAFF_COD: "",
  STAFF_NAM: "",
  ID_CAR: "",
  STAFF_GENDE: "",
  TELEPHON: "",
  STAFF_TYP: "",
  AFFILIATIO: "",
})
const loading = ref(false)
const displayedPlanData = ref([])


const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const rowKey = (row) => row.ID // 设置行的唯一标识

const selectedIds = ref([])
const viewingItem = ref(null)




const displayedApplications = ref([])
const alltabledata = (data) => {
  displayedApplications.value = data

}
const searchApplications = async () => {
  displayedApplications.value = []
  try {
    const response = await axios.get(`${apiBaseUrl.value}/application/review/search`, { params: search.value })
    applications.value = response.data
  } catch (error) {
    console.error('搜索申请失败:', error)
    alert('搜索申请失败: ' + (error.response?.data?.message || error.message))
  }
}

const resetSearch = () => {
  search.value = {
    STAFF_NAME: '',
    ID_CARD: '',
    AU_STATUS: ''
  }
  searchApplications()
}

const reviewApplicationss = (application) => {
  isViewDialogOpen.value = true
  reviewForm.value = {
    ...application
    // ID: application.ID,
    // STAFF_CODE: application.STAFF_CODE,
    // STAFF_NAME: application.STAFF_NAME,
    // ID_CARD: application.ID_CARD,
    // STAFF_GENDER: application.STAFF_GENDER,
    // TELEPHONE: application.TELEPHONE,
    // STAFF_TYPE: application.STAFF_TYPE,
    // AFFILIATION: application.AFFILIATION,
    // STAMP: application.STAMP
  }
  reservationreviewForm.value.ID = application.ID
  reservationreviewForm.value.AUTHORIZATION_TYPE = application.AUTHORIZATION_TYPE
  reservationreviewForm.value.END_TIME = dayjs(application.END_TIME).format('YYYY-MM-DD hh:mm:ss')
  isReviewDialogOpen.value = true
}
const reviewApplication = async (application) => {

  reviewForm.value = {
    ...application
  }
  reservationreviewForm.value.ID = application.ID
  reservationreviewForm.value.AUTHORIZATION_TYPE = application.AUTHORIZATION_TYPE
  isReviewDialogOpen.value = true

  // const response = await axios.get(`${apiBaseUrl.value}/download/${application.value.PAPERS}`)
  // imgdata.value.push(response.data.url)
}

const closeReviewDialog = () => {
  isReviewDialogOpen.value = false
  isViewDialogOpen.value = false
}


const submitReview = async (item) => {
  reservationreviewForm.value.AU_STATUS = item
  reservationreviewForm.value.APPLICATION_STATUS = item == '通过' ? '通过' : '未通过'
  try {
    await axios.put(`${apiBaseUrl.value}/application/${reservationreviewForm.value.ID}/review`, reservationreviewForm.value)
    alert('审核提交成功')

    closeReviewDialog()
    await searchApplications()
  } catch (error) {
    console.error('审核提交失败:', error)
    alert('审核提交失败: ' + (error.response?.data?.message || error.message))
  }
}

const viewDetails = (item) => {
  viewingItem.value = item
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingItem.value = null
}


const getStatusClass = (status) => {
  const classMap = {
    '待审核': 'bg-yellow-100 text-yellow-800',
    '通过': 'bg-green-100 text-green-800',
    '未通过': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

onMounted(() => {
  searchApplications()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>
